package com.inexas.cu.client.pipe;

import com.google.gwt.core.client.*;
import com.google.gwt.event.shared.*;
import com.google.gwt.user.client.rpc.*;
import com.google.inject.*;

@Singleton
public class PipeClientEndImpl implements PipeClientEnd, RequestHandler<AbstractRequest> {
	private static boolean initialized = false;
	private final PipeServiceAsync rpcService = GWT.create(PipeService.class);
	private final HandlerManager eventBus;
	private String credentials = null;
	
	@Inject
	public PipeClientEndImpl(HandlerManager eventBus) {
		assert !initialized;
		
		this.eventBus = eventBus;
		
		eventBus.addHandler(AbstractRequest.getType(), this);
		initialized = true;
    }

	public void onFired(RequestEvent<AbstractRequest> event) {
		final AbstractRequest request = event.getRequest();
		request.setRequestId();
		request.setCredentials(credentials);
		rpcService.process(request, new AsyncCallback<AbstractResponse>() {

			public void onFailure(Throwable e) {
				// todo Handle RPC failures appropriately in pipe: create an event!
				e.printStackTrace();
                throw new RuntimeException("How about implementing me?!");
            }

			public void onSuccess(AbstractResponse response) {
				eventBus.fireEvent(new ResponseEvent<AbstractResponse>(response));
            }
			
		});
     }

	public void setCredentials(String credentials) {
		this.credentials = credentials;
    }

}
